package com.jinbei.common.socket;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zflu
 * 该类为提供外部 socket链接访问
 * Created by lucky on 2018/7/31.
 */
@ServerEndpoint("/messageSocket/{uid}")
@Component
public class MessageWebSocket {

    private final Logger logger = LoggerFactory.getLogger(MessageWebSocket.class);

    /**
     * 记录连接数
     */
    private static AtomicInteger onlineCount = new AtomicInteger();

    /**
     * 回话对象
     */
    private static Map<String,MessageWebSocket> webSocketMap = new ConcurrentHashMap<>();

    /**
     * session对象
     */
    private Session session;

    /**
     * 用户id
     */
    private String uid;


    /**
     * @author zflu
     * @Description   打开链接
     * @date 2018/7/31 19:03
     * @param session
     * @return void
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("uid") String uid) {
        this.session = session;
        this.uid = uid;
        webSocketMap.put(uid,this);
        //连接数量++
        addOnline();
        try {
            logger.info("有客户端连接成功..... ");
        }catch (Exception e){
            logger.error("客户端连接失败..... ",e.getMessage());
        }
    }

    /**
     * @author zflu
     * @Description 关闭链接
     * @date 2018/7/31 19:03
     * @param
     * @return void
     */
    @OnClose
    public void onClose() {
        webSocketMap.remove(this.uid);
        //连接数--
        closeOnline();
        logger.info("有客户端链接断开...... ");
    }

    /**
     * @author zflu
     * @Description   异常错误
     * @date 2018/7/31 19:35
     * @param session, error
     * @return void
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("web socket error...... ,内容是: ",error);
    }

    /**
     * @author zflu
     * @Description  推送消息
     * @date 2018/7/31 19:06
     * @param message
     * @return void
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * @author zflu
     * @Description   推送消息给连接socket客户端
     * @date 2018/7/31 19:32
     * @param message 发送的消息
     * @param uid 连接用户id
     * @return void
     */
    public void sendAllSocketMessage(String message , String uid) throws IOException {
        //如果没有socket连接
        if(webSocketMap.isEmpty()){
            return;
        }
        //有连接
        if(StringUtils.isBlank(uid)){
            Iterator<Map.Entry<String, MessageWebSocket>> it = webSocketMap.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry<String, MessageWebSocket> next = it.next();
                next.getValue().sendMessage(message);
            }
        }else{
            webSocketMap.get(uid).sendMessage(message);
        }
    }

    /**
     * @author zflu
     * @Description   连接数 ++
     * @date 2018/7/31 19:24
     * @param
     * @return void
     */
    public void addOnline(){
        onlineCount.getAndIncrement();
    }

    /**
     * @author zflu
     * @Description   连接数--
     * @date 2018/7/31 19:25
     * @param
     * @return void
     */
    public void closeOnline(){
        onlineCount.getAndDecrement();
    }

    /**
     * @author zflu
     * @Description   统计连接数
     * @date 2018/7/31 19:26
     * @param
     * @return int
     */
    public int countOnline(){
        return onlineCount.get();
    }


}
